package config

import (
	"api-gateway-core/common"
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"log"
)

var (
	Address       = ""
	GroupId       = ""
	GatewayId     = ""
	GatewayName   = ""
	GatewayHost   = ""
	GatewayPort   = ""
	Configuration *common.Configuration
	Channel       <-chan *redis.Message
)

func ConfInit() {
	viperInit()
	variableInit()
	redisInit()
	appRegister()
}

// 变量初始化
func variableInit() {
	Address = viper.GetString("api-gateway.address")
	GroupId = viper.GetString("api-gateway.groupId")
	GatewayId = viper.GetString("api-gateway.gatewayId")
	GatewayName = viper.GetString("api-gateway.gatewayName")
	GatewayHost = viper.GetString("api-gateway.gatewayHost")
	GatewayPort = viper.GetString("api-gateway.gatewayPort")
}

func viperInit() {
	viper.SetConfigName("config") // name of config file (without extension)
	viper.SetConfigType("yaml")   // REQUIRED if the config file does not have the extension in the name
	viper.AddConfigPath(".")
	err := viper.ReadInConfig() // 查找并读取配置文件
	if err != nil {             // 处理读取配置文件的错误
		panic(fmt.Errorf("Fatal error config file: %w \n", err))
	} // path to look for the config file in
}

func redisInit() {
	redisClient := redis.NewClient(&redis.Options{
		Addr: viper.GetString("redis.addr"),
	})
	//订阅channel接收信息
	Channel = redisClient.Subscribe(context.Background(), GatewayId).Channel()
	go func() {
		for {
			select {
			case msg := <-Channel:
				log.Println("接收到信息========" + msg.Payload)
				appPull(msg.Payload)
			}
		}
	}()
}
